package com.mc.lp.database.dao.impl.cachable;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.util.CollectionUtils;

import com.mc.lp.database.dao.IRolePermissionDAO;
import com.mc.lp.database.dao.impl.AbstractGenericHibernateDAO;
import com.mc.lp.database.entity.PermissionEntity;
import com.mc.lp.database.entity.RoleEntity;
import com.mc.lp.shared.vo.KeyValueMap;

public class RolePermissionDAOImpl extends AbstractGenericHibernateDAO<RoleEntity, Long, IRolePermissionDAO> implements IRolePermissionDAO{
	/**
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * recursive method to resolve the permissions
	 */
	public Set<PermissionEntity>  resolvePermissionsByRoleId(List<RoleEntity> entities,Set<PermissionEntity> finalList) {
			RoleEntity entity =null;
			List<RoleEntity> nextIterationRoles= new ArrayList<RoleEntity>();
			nextIterationRoles.addAll(entities);
			if(!CollectionUtils.isEmpty(nextIterationRoles)){
				entity=entities.get(0);
				//remove the current role to make it eligible for next iteration.
				nextIterationRoles.remove(entities.get(0));
				//add all permission from current role item
				finalList.addAll(entity.getPermissions());
				KeyValueMap map = new KeyValueMap();
				map.addKeyValue("parentRoleId", entity.getId());
				//search if any child exists
				List<RoleEntity> roles = findByProperties(map);
				//add all child for next iteration
				nextIterationRoles.addAll(roles);
				if(!CollectionUtils.isEmpty(nextIterationRoles)){
					//recursively call this method till all children dies
					return resolvePermissionsByRoleId(nextIterationRoles,finalList);
				}
			}
		return finalList;
	}
}
